package com.cx.zyx.modulebiz.news.config;

import com.github.benmanes.caffeine.cache.Caffeine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.lang.reflect.Method;
import java.time.Duration;
import java.util.List;

@Slf4j
@Configuration
@EnableCaching // 启用 Spring 缓存
public class CacheConfig {
    @Bean("caffeine")
    @Primary
    public CacheManager caffeineCacheManager() {
        log.info("-=-=-=-=-=-装载CaffeineCache缓存-=-=-=-=-=-");
        // 创建 CaffeineCacheManager
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        // 配置 Caffeine 缓存
        cacheManager.setCaffeine(Caffeine.newBuilder()
                // 设置最大容量为 100
                .maximumSize(100)
                // 设置写入后 10 分钟过期
                .expireAfterWrite(10, java.util.concurrent.TimeUnit.MINUTES)
                // 启用统计
                .recordStats());
        // 设置缓存名称（可选，Spring Boot 可通过 application.yaml 指定）
        cacheManager.setCacheNames(List.of("news"));
        return cacheManager;
    }

    @Bean("redis")
    public CacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory) {
        log.info("-=-=-=-=-=-装载Redis缓存-=-=-=-=-=-");
        // 默认的 RedisCacheConfiguration
        RedisCacheConfiguration defaultCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                // 设置缓存的默认有效期为 1 小时
                .entryTtl(Duration.ofHours(1))
                // 禁止缓存空值
                .disableCachingNullValues()
                // 设置键的序列化器为 StringRedisSerializer
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                // 设置值的序列化器为 GenericJackson2JsonRedisSerializer (可以序列化Java对象为JSON)
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));

        // 构建 RedisCacheManager
        return RedisCacheManager.builder(redisConnectionFactory)
                .cacheDefaults(defaultCacheConfiguration)
                .build();
    }

    // 覆盖默认的 KeyGenerator
    //@Bean
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                // 实现你自己的默认键生成逻辑
                // 例如：返回方法名 + 所有参数的简单拼接
                StringBuilder sb = new StringBuilder();
                sb.append(method.getName());
                for (Object param : params) {
                    if (param != null) {
                        sb.append("_").append(param.toString());
                    }
                }
                return sb.toString();
            }
        };
    }
}
